<template>
  <a-modal
    v-model:visible="visible"
    title="选择用户"
    :width="600"
    :ok-text="'确定'"
    :cancel-text="'取消'"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="role-user-tree">
      <!-- 搜索框 -->
      <a-input
        v-model:value="searchKeyword"
        placeholder="搜索用户名称"
        allow-clear
        style="margin-bottom: 16px"
        @change="handleSearch"
      />
      
      <!-- 角色-用户树 -->
      <div v-if="roleUserTree.length > 0" class="tree-container">
        <div 
          v-for="role in roleUserTree" 
          :key="role.id" 
          class="role-item"
        >
          <!-- 角色标题 -->
          <div 
            class="role-header"
            @click="toggleRole(role.id)"
          >
            <a-checkbox 
              v-if="multiple"
              :checked="isRoleChecked(role.id)"
              :indeterminate="isRoleIndeterminate(role.id)"
              @change="(e) => handleRoleCheck(e, role.id)"
            />
            <a-collapse-transition>
              <span class="expand-icon" :class="{ 'expanded': expandedRoles.includes(role.id) }">
                {{ expandedRoles.includes(role.id) ? '▼' : '▶' }}
              </span>
            </a-collapse-transition>
            <span class="role-name">{{ role.name }}</span>
            <!-- 加载中状态 -->
            <span v-if="loadingRoles.includes(role.id)" class="loading-indicator">
              <a-spin size="small" />
            </span>
          </div>
          
          <!-- 角色下的用户列表 -->
          <a-collapse-transition>
            <div v-if="expandedRoles.includes(role.id)" class="user-list">
              <div v-if="!role.users || role.users.length === 0" class="empty-user-tip">
                暂无用户数据
              </div>
              <div 
                v-for="user in role.users" 
                :key="user.id"
                class="user-item"
              >
                <a-checkbox 
                  v-if="multiple"
                  :checked="selectedUserIds.includes(user.id)"
                  @change="(e) => handleUserCheck(e, user.id)"
                />
                <a-radio 
                  v-else
                  :checked="selectedUserIds[0] === user.id"
                  @change="(e) => handleUserCheck(e, user.id)"
                />
                <span class="user-name">{{ user.name }}</span>
                <span class="user-info">{{ user.department }} - {{ user.position }}</span>
              </div>
            </div>
          </a-collapse-transition>
        </div>
      </div>
      
      <!-- 无数据提示 -->
      <div v-else class="empty-tip">暂无角色数据</div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import { message } from 'ant-design-vue';
import { getUserDataListByParam } from '@/api/syssetting/user';
import { getAllRoleListData } from '@/api/syssetting/role';

// 定义组件的Props
interface SelectUserProps {
  visible: boolean;
  multiple?: boolean;
  defaultUserIds?: string[];
  onConfirm: (userIds: string[]) => void;
  onCancel: () => void;
}

// 定义用户和角色的类型
interface User {
  id: string;
  name: string;
  department: string;
  position: string;
  roleIds: string[];
}

interface Role {
  id: string;
  name: string;
  users: User[];
}

// 接收Props
const props = defineProps<SelectUserProps>();

// 响应式数据
const visible = ref(false);
const multiple = ref(props.multiple ?? false);
const searchKeyword = ref('');
const expandedRoles = ref<string[]>([]);
const selectedUserIds = ref<string[]>([]);
const roleUserTree = ref<Role[]>([]);
const loadingRoles = ref<string[]>([]); // 记录正在加载用户数据的角色ID

// 监听visible变化
watch(() => props.visible, (newValue) => {
  visible.value = newValue;
  if (newValue) {
    // 打开模态框时重置数据
    selectedUserIds.value = props.defaultUserIds?.slice() || [];
    loadRoleData();
  }
});

// 加载角色数据
const loadRoleData = async () => {
  try {
    // 重置数据
    roleUserTree.value = [];
    expandedRoles.value = [];
    loadingRoles.value = [];
    
    // 获取所有角色
    const roleResponse = await getAllRoleListData();
    const roleData = roleResponse.data?.Data || [];
    
    // 格式化角色数据，不包含用户信息
    roleUserTree.value = roleData.map((role: any) => ({
      id: String(role.Id || role.id || ''),
      name: role.Name || role.name || '未知角色',
      users: [] as User[] // 初始时不加载用户数据
    }));
    
    console.log('加载角色数据完成:', roleUserTree.value.length);
  } catch (error) {
    console.error('加载角色数据失败:', error);
    message.error('加载角色数据失败');
    roleUserTree.value = [];
  }
};

// 根据角色ID加载用户数据
const loadUsersByRoleId = async (roleId: string) => {
  try {
    // 如果已经在加载中，则不再重复加载
    if (loadingRoles.value.includes(roleId)) {
      return;
    }
    
    loadingRoles.value.push(roleId);
    
    // 获取所有用户数据
    const userResponse = await getUserDataListByParam({RoleId: roleId});
    const userData = userResponse.data?.Data || [];
    
    // 格式化用户数据
    const allUsers: User[] = userData.map((user: any) => ({
      id: String(user.Id || user.id || ''),
      name: user.RealName || user.name || '未知用户',
      department: user.DepartmentName || user.department || '',
      position: user.PositionName || user.position || '',
      roleIds: Array.isArray(user.RoleIdList) ? user.RoleIdList.map((id: any) => String(id)) : 
               Array.isArray(user.roleIds) ? user.roleIds.map((id: any) => String(id)) : []
    }));
    
    // 找到对应的角色
    const role = roleUserTree.value.find(r => r.id === roleId);
    if (role) {
      // 筛选出属于当前角色的用户
      role.users = allUsers;
      
      // 应用搜索过滤
      if (searchKeyword.value.trim()) {
        const keyword = searchKeyword.value.trim().toLowerCase();
        role.users = role.users.filter(user => 
          user.name.toLowerCase().includes(keyword)
        );
      }
    }
    
    console.log(`加载角色ID ${roleId} 的用户数据完成:`, role?.users?.length);
  } catch (error) {
    console.error(`加载角色ID ${roleId} 的用户数据失败:`, error);
    message.error('加载用户数据失败');
  } finally {
    // 移除加载状态
    loadingRoles.value = loadingRoles.value.filter(id => id !== roleId);
  }
};

// 处理搜索
const handleSearch = () => {
  // 重新加载已展开角色的用户数据，应用搜索过滤
  expandedRoles.value.forEach(roleId => {
    loadUsersByRoleId(roleId);
  });
};

// 切换角色展开/折叠
const toggleRole = async (roleId: string) => {
  const index = expandedRoles.value.indexOf(roleId);
  if (index > -1) {
    // 折叠角色
    expandedRoles.value.splice(index, 1);
  } else {
    // 展开角色并加载用户数据
    expandedRoles.value.push(roleId);
    await loadUsersByRoleId(roleId);
  }
};

// 检查角色是否被全选
const isRoleChecked = (roleId: string) => {
  const role = roleUserTree.value.find(r => r.id === roleId);
  if (!role || !role.users) return false;
  
  return role.users.every(user => selectedUserIds.value.includes(user.id));
};

// 检查角色是否处于半选状态
const isRoleIndeterminate = (roleId: string) => {
  const role = roleUserTree.value.find(r => r.id === roleId);
  if (!role || !role.users) return false;
  
  const checkedCount = role.users.filter(user => 
    selectedUserIds.value.includes(user.id)
  ).length;
  
  return checkedCount > 0 && checkedCount < role.users.length;
};

// 处理角色复选框变化
const handleRoleCheck = (e: any, roleId: string) => {
  const role = roleUserTree.value.find(r => r.id === roleId);
  if (!role || !role.users) return;
  
  if (e.target.checked) {
    // 全选角色下的所有用户
    role.users.forEach(user => {
      if (!selectedUserIds.value.includes(user.id)) {
        selectedUserIds.value.push(user.id);
      }
    });
  } else {
    // 取消选择角色下的所有用户
    selectedUserIds.value = selectedUserIds.value.filter(
      userId => !role.users.some(user => user.id === userId)
    );
  }
};

// 处理用户复选框变化
const handleUserCheck = (e: any, userId: string) => {
  if (multiple.value) {
    if (e.target.checked) {
      if (!selectedUserIds.value.includes(userId)) {
        selectedUserIds.value.push(userId);
      }
    } else {
      selectedUserIds.value = selectedUserIds.value.filter(id => id !== userId);
    }
  } else {
    // 单选模式
    selectedUserIds.value = [userId];
  }
};

// 确认选择
const handleOk = () => {
  if (selectedUserIds.value.length === 0) {
    message.warning('请至少选择一个用户');
    return;
  }
  props.onConfirm(selectedUserIds.value);
};

// 取消选择
const handleCancel = () => {
  selectedUserIds.value = [];
  searchKeyword.value = '';
  props.onCancel();
};
</script>

<style scoped lang="scss">
.role-user-tree {
  max-height: 400px;
  overflow-y: auto;
  padding-right: 8px;
}

.tree-container {
  .role-item {
    margin-bottom: 12px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .role-header {
    padding: 12px 16px;
    background-color: #fafafa;
    cursor: pointer;
    display: flex;
    align-items: center;
    transition: background-color 0.3s;
    
    &:hover {
      background-color: #f0f0f0;
    }
    
    .expand-icon {
      width: 16px;
      height: 16px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      margin: 0 8px;
      transition: transform 0.3s;
    }
    
    .role-name {
      font-weight: 500;
    }
    
    .loading-indicator {
      margin-left: auto;
    }
  }
  
  .user-list {
    padding: 8px 0;
  }
  
  .user-item {
    padding: 8px 48px;
    display: flex;
    align-items: center;
    transition: background-color 0.3s;
    
    &:hover {
      background-color: #fafafa;
    }
    
    .user-name {
      margin-left: 8px;
      font-weight: 500;
    }
    
    .user-info {
      margin-left: 16px;
      color: #8c8c8c;
      font-size: 12px;
    }
  }
  
  .empty-user-tip {
    padding: 16px 48px;
    color: #8c8c8c;
    font-size: 12px;
  }
}

.empty-tip {
  text-align: center;
  color: #8c8c8c;
  padding: 40px 0;
}

// 滚动条样式
.role-user-tree::-webkit-scrollbar {
  width: 6px;
}

.role-user-tree::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.role-user-tree::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.role-user-tree::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>